﻿using CronExpressionDescriptor;
using Cronos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib.CronHelper
{
    public class CronOp
    {
        /// <summary>
        /// 获取cron的表达式描述
        /// </summary>
        /// <param name="cronString"></param>
        /// <param name="lang">语言 zh-CN  en   ja </param>
        /// <returns></returns>
        public string GetDescription(string cronString,string lang= "zh-CN")
        {
           return ExpressionDescriptor.GetDescription("0-10 11 * * *", new Options()
            {
                DayOfWeekStartIndexZero = false,
                Use24HourTimeFormat = true,
                Locale = lang
           });
        }

        /// <summary>
        ///     获取cron表达式的下一次执行时间     
        /// </summary>
        /// <param name="cronString"> "* * * * *"</param>
        /// <param name="timezone"> 时区</param>
        /// <returns></returns>
        public static DateTime? GetNextTime(string cronString,string timezone="")
        {
            CronExpression expression = CronExpression.Parse(cronString);
            TimeZoneInfo tzi = string.IsNullOrEmpty(timezone) ? TimeZoneInfo.FindSystemTimeZoneById("China Standard Time") : TimeZoneInfo.Local;

            return expression.GetNextOccurrence(DateTime.UtcNow, tzi);
        }

        /// <summary>
        /// 获取在时间段内符合cron表达式的时间列表
        /// </summary>
        /// <param name="cronString">cron表达式</param>
        /// <param name="beginDt">开始时间</param>
        /// <param name="endDt">结束时间</param>
        /// <param name="timezone">时区</param>
        /// <returns></returns>
        public List<DateTime> GetNextTime(string cronString, DateTime beginDt,DateTime endDt  ,string timezone)
        {
            CronExpression expression = CronExpression.Parse(cronString);
            TimeZoneInfo tzi = string.IsNullOrEmpty(timezone) ? TimeZoneInfo.FindSystemTimeZoneById("China Standard Time") : TimeZoneInfo.Local;

            return expression.GetOccurrences(beginDt,endDt, tzi).ToList();
        }






    }
}
